<?php
namespace Hive\Ressource\Source\Parser;
/**
 * Source Parder Object.
 *
 * It will be used to parse the copy/paste URL and extratc the user id in 
 * the target source.
 *
 * @author Xavier VILAIN
 * @package Hive\Ressource\Source\Parser
 * @license #hive-license-social#
 *
 * @property string	$type			Id of the Source
 * @property string	$label			Source name
 * @property bool	$standard		Is a standard type (can't be deleted)
 * @property bool	$active			Is an active type (can be selected)
 */
class Linkedin {
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $url
	 */
	public static function parse($url) {
		
	}
	
	/**
	 * 
	 */
	public static function connectionUri() {
		$redirectUrl = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'].'?mod=users&act=social&sac=linkedin';
		$userid = \User::current()->getId();
		$params = array('response_type' => 'code',
                   	 	'client_id' => LINKEDIN_API_KEY,
                    	'scope' => 'r_fullprofile r_emailaddress r_network',
                    	'state' => uniqid('', true), // unique long string
                    	'redirect_uri' => $redirectUrl);
 
    	// Authentication request
    	$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
    	// Needed to identify request when it returns to us
	    $_SESSION['linkedin-state'] = $params['state'];

        return $url;
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public static function checkConnectionToken() {
		$error = \Xview::instance()->val('error');
		if(!empty($error)) {
			$error = \Xview::instance()->val('error_description');
			\Fox\Message::Error($error);
			return;
		}
			
		$code = \Xview::instance()->val('code');
		if(!empty($code)) {
			$state = \Xview::instance()->val('state');
			if($_SESSION['linkedin-state'] == $state) {
				self::accessToken($code);
				unset($_SESSION['linkedin-state']);
			} else {
				return;
			}
		}
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public static function accessToken($code) {
		if(empty($_SESSION['linkedin-access_token'])) {
			$redirectUrl = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'].'?mod=users&act=social&sac=linkedin';
		    $params = array('grant_type' => 'authorization_code',
		                    'client_id' => LINKEDIN_API_KEY,
		                    'client_secret' => LINKEDIN_API_SECRET,
		                    'code' =>$code,
		                    'redirect_uri' => $redirectUrl,
		              );
	     	
	    	// Access Token request
	    	$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
	     
			// Tell streams to make a POST request
	    	$context = stream_context_create(
	                    array('http' => 
	                        array('method' => 'POST',
	                        )
	                    )
	                );
	        try {  
		    	// Retrieve access token information
		    	$response = file_get_contents($url, false, $context);
		 		if(empty($response)) {
		 			\User::current()->setPrefs('linkedin-json-token',null);
		 			throw new \Exception(\Msg(\Hive::BUNDLE,\Hive::SOCIAL_LINKEDIN_CONNECCTION_ERROR));
		 		}
		 		
		    	// Native PHP object, please
		    	$token = json_decode($response);
			    // Store access token and expiration time
			    $_SESSION['linkedin-access_token'] = $token->access_token; // guard this! 
			    $_SESSION['linkedin-expires_in']   = $token->expires_in; // relative time (in seconds)
			    $_SESSION['linkedin-expires_at']   = time() + $_SESSION['linkedin-expires_in']; // absolute time
			    \User::current()->setPrefs('linkedin-json-token',$response);
			    \Fox\Message::Success(Msg(\Hive::BUNDLE,\Hive::SOCIAL_LINKEDIN_CONNECTION_SUCCESS));
	         } catch(\Exception $e) {
	         	
	         	$_SESSION['linkedin-access_token'] = null;
	         	$_SESSION['linkedin-expires_in']   = null;
	         	$_SESSION['linkedin-expires_at']   = null;
	         	\Fox\Message::Error($e);
	         }
		} else {
			\Fox\Message::Success(Msg(\Hive::BUNDLE,\Hive::SOCIAL_LINKEDIN_CONNECTION_SUCCESS));
		}
	}
	
	/**
	 * Fetch Queries
	 * 
	 */
	public static function fetch($method, $resource, $body = '') {
		$token = null;
		// Check Connection
		if(empty($_SESSION['access_token'])) {
			// Try to load from preferences
			$token = \User::current()->getPrefs('linkedin-json-token');
			if(!empty($token)) {
				$token = json_decode($token);
				$_SESSION['linkedin-access_token'] = $token->access_token; // guard this! 
	    		$_SESSION['linkedin-expires_in']   = $token->expires_in; // relative time (in seconds)
	    		$_SESSION['linkedin-expires_at']   = time() + $_SESSION['linkedin-expires_in']; // absolute time
				if ((empty($_SESSION['linkedin-expires_at'])) || (time() > $_SESSION['linkedin-expires_at'])) {
			        // Token has expired, clear the state
			        $_SESSION['linkedin-access_token'] = null;
			        $_SESSION['linkedin-expires_in'] = null;
			        $_SESSION['linkedin-expires_at'] = null;
			        // Should Set a warning message
			    }
			}
		}
		
		if(empty($_SESSION['linkedin-access_token']) && !empty($token)) {
			// User may not want to retrieve the data
			\Fox\Message::Warning(Msg(\Hive::BUNDLE,\Hive::SOCIAL_LINKEDIN_OUT_OF_SYNC));
			return;
		} elseif(empty($_SESSION['linkedin-expires_at']) || (time() > $_SESSION['linkedin-expires_at']))  {
			\Fox\Message::Warning(Msg(\Hive::BUNDLE,\Hive::SOCIAL_LINKEDIN_OUT_OF_SYNC));
			return;
		} elseif(empty($_SESSION['linkedin-access_token'])) {
			// Never give asscess to linked in
			return;
		}
		
		$params = array('oauth2_access_token' => $_SESSION['linkedin-access_token'],
                    'format' => 'json',
              );
     
	    // Need to use HTTPS
	    $url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
	    // Tell streams to make a (GET, POST, PUT, or DELETE) request
	    $context = stream_context_create(
	                    array('http' => 
	                        array('method' => $method,
	                        )
	                    )
	                );
	 
	 
	    // Hocus Pocus
	    $response = file_get_contents($url, false, $context);
	 	echo($response);
	    // Native PHP object, please
	    return json_decode($response,true);
	}
}